import re

from .models import User
from django.contrib.auth.backends import ModelBackend

def get_user_by_account(account):
    """判断输入数据是用户名或手机号"""
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None

    return user


class UsernameModelBackend(ModelBackend):
    """自定义backend类，重写authenticate()"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None
